﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using DCTLib.Common;

public partial class Members_mua_ban_banner : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string confirm = Request.QueryString["confirm"].ToString();
            int point = 0;
            try
            {
                point = int.Parse(Request.QueryString["point"]);
            }
            catch { point = 0; }
            int productId;
            try
            {
                productId = int.Parse(Request.QueryString["productId"]);
            }
            catch { productId = 0; }

            if (Request.QueryString["confirm"] != null && !string.IsNullOrEmpty(Request.QueryString["confirm"]))
            {
                if (confirm == "false" && point > 0 && productId > 0)
                {
                    string msg = string.Format(@"Bạn có đồng ý đặt banner với số điểmm {0} points? <br/> 
                        <a href='mua-ban-banner.aspx?productId={1}&point={0}&confirm=true'>Click vào đây để xác thực</a>", point, productId);                    
                    lblAlert.Text = msg;
                }
                else
                {
                    try
                    {
                        string username = Session["User"].ToString();
                        point = int.Parse(Request.QueryString["point"]);
                        productId = int.Parse(Request.QueryString["productId"]);

                        //Khi click vào Banner thì gọi tới hàm này để xử lý tính toán điểm cho các cấp.
                        ExecCalculatePoint(username, point, productId);
                    }
                    catch
                    {
                        lblAlert.Text = "<font color='red'><b>[Hệ thống quá tải, bạn vui lòng thử lại]</b></font>";                        
                    }
                }
            }
        }
    }

    protected void ExecCalculatePoint(string username, decimal point, int productId)
    {
        //Update lại số điểm mà username này order
        string sql = string.Format(@"            
            DECLARE @memID int
            SET @memID = (SELECT MemberID FROM Web_Members WHERE username='{0}')
            DECLARE @currentPoint decimal(18,2)
            SET @currentPoint = 
            (
	            SELECT PointNumber FROM [Property] WHERE 
	            MemberID=(SELECT MemberID FROM Web_Members WHERE username='{0}')
            )
            IF(@currentPoint-{1}>=0)
            BEGIN 
                DECLARE @LastMoney decimal(20,2)
                SET @LastMoney = (SELECT (PointNumber-{1}) FROM [Property] WHERE MemberID=@memID)
                SET XACT_ABORT ON  
	            BEGIN TRAN  
	            BEGIN TRY 
                    UPDATE [Property]
                    SET PointNumber = @LastMoney
                    WHERE MemberID=@memID
                    
                    INSERT INTO OrderDetails(MemberID,ProductID,UnitPrice)
		            VALUES(@memID,{2},{1})

                    INSERT INTO TransactionLogs(MemberID,FirstMoney,LastMoney,ReasonChange)
		            VALUES(@memID,@currentPoint,@LastMoney,N'Giao dịch {1} points')

                    COMMIT
	                SELECT 'true'
                END TRY 
                BEGIN CATCH  
                   ROLLBACK  
                   SELECT 'false'
                END CATCH
            END 
            ELSE SELECT 'false'", username, point, productId);
        bool isValid = bool.Parse(SQLHelper.TExecuteScalar(sql).ToString());

        //Lấy ra UniqueCode của User hiện tại mua hàng.
        sql = string.Format("select uniquecode FROM Web_Members where username='{0}'", username);
        string uniquecode = SQLHelper.TExecuteScalar(sql).ToString();
        string[] arrUserLevels = uniquecode.Split('|');
        List<string> listUserIDLevels = new List<string>();
        if (arrUserLevels.Length > 1)
        {
            for (int i = 0; i < arrUserLevels.Length - 1; i++)
            {
                listUserIDLevels.Add(arrUserLevels[i]);
            }
        }      

        string sqlTransBeginTry = @"
                SET XACT_ABORT ON  
	            BEGIN TRAN  
	            BEGIN TRY ";
        string sqlTransEndTry = @"
                    SELECT 'true'
		            COMMIT
                END TRY ";
        string sqlTransCatch = @"
                BEGIN CATCH  
                   ROLLBACK  
                   SELECT 'false'
                END CATCH";
        string sqlQuery = string.Empty;
        if (listUserIDLevels != null && listUserIDLevels.Count > 0)
        {
            if (isValid)
            {
                sqlQuery += @"
                    DECLARE @FirstMoney decimal(18,2)
                    DECLARE @LastMoney decimal(20,2)";
                //Lấy thông tin bảng Config
                //Đếm xem có bao nhiêu cấp trong bảng Configs
                sql = string.Format(@"SELECT top 1 * FROM Configs ORDER BY NumOfPeople");
                DataTable tbTmpLevels = SQLHelper.GetAll(sql);
                int iNumOfPeopleFilted = 0;
                decimal dPercentPoint = 0;
                int itemp = 0;
                if (tbTmpLevels != null && tbTmpLevels.Rows.Count == 1)
                {
                    iNumOfPeopleFilted = int.Parse(tbTmpLevels.Rows[0]["NumOfPeople"].ToString());
                    dPercentPoint = decimal.Parse(tbTmpLevels.Rows[0]["percent"].ToString());
                }

                if (listUserIDLevels.Count >= iNumOfPeopleFilted)
                    itemp = iNumOfPeopleFilted;
                else
                    itemp = listUserIDLevels.Count;
                for (int m = 0; m < itemp; m++)
                {
                    int memID = int.Parse(listUserIDLevels[m].ToString());
                    sqlQuery += string.Format(@"                        
                                    SET @FirstMoney = 
                                    (
                                        SELECT PointNumber FROM [Property] WHERE 
                                        MemberID={0}
                                    )", memID);
                    sqlQuery += "\n";

                    //Cộng phần trăm điểm cho các cấp
                    sqlQuery += string.Format(@"
                                        update [Property]
                                        set pointNumber = (pointNumber+(cast({0} AS decimal(20,2))/100)*{1})
                                        WHERE MemberID={2}", dPercentPoint, point, memID);
                    sqlQuery += "\n";

                    sqlQuery += string.Format(@"                        
                                        SET @LastMoney = (SELECT PointNumber FROM [Property] WHERE MemberID={0})
                                        INSERT INTO TransactionLogs(MemberID,FirstMoney,LastMoney,ReasonChange)
                                        VALUES({0},@FirstMoney,@LastMoney,N'Ăn hoa hồng {3}% khi user ""{1}"" giao dich {2} points')"
                        , memID, username, point, dPercentPoint);
                    sqlQuery += "\n";
                }
                for (int j = 0; j < listUserIDLevels.Count; j++)
                {
                    //Cộng phần trăm điểm userID giới thiệu Trực tiếp đc tuyến dưới
                    int memIDOut = int.Parse(listUserIDLevels[j].ToString());
                    string sqlPercentPoint = string.Format(@"
                                        DECLARE @percent decimal(20,2)
                                        DECLARE @value decimal(20,2)

                                        SET @percent = (select [percent] from [LevelConfigs]
                                        where numofpeople=(SELECT count(*) FROM Web_Members WHERE UniqueCode like '{0}|%'))

                                        set @value= (cast(@percent AS decimal(20,2))/100)*{1}
                                        if(@value is not null)
                                            select @value
                                        else
                                            select 0", memIDOut, point);
                    decimal dPercent = decimal.Parse(SQLHelper.TExecuteScalar(sqlPercentPoint).ToString());
                    decimal percentNumber = decimal.Parse(SQLHelper.TExecuteScalar(sqlPercentPoint.Replace("select @value", "select @percent")).ToString());

                    if (dPercent > 0)
                    {
                        sqlQuery += string.Format(@"                        
                                            SET @FirstMoney = 
                                            (
                                                SELECT PointNumber FROM [Property] WHERE 
                                                MemberID={0}
                                            )", memIDOut);
                        sqlQuery += "\n";

                        sqlQuery += string.Format(@"
                                            update [Property]
                                            set pointNumber = (pointNumber+{0})
                                            WHERE MemberID={1}", dPercent, memIDOut);
                        sqlQuery += "\n";

                        sqlQuery += string.Format(@"                        
                                            SET @LastMoney = (SELECT PointNumber FROM [Property] WHERE MemberID={0})
                                            INSERT INTO TransactionLogs(MemberID,FirstMoney,LastMoney,ReasonChange)
	                                        VALUES({0},@FirstMoney,@LastMoney,N'Ăn hoa hồng Trực tiếp {3}% khi user ""{1}"" giao dich {2} points - Do có công giới thiệu tuyến dưới')"
                            , memIDOut, username, point, percentNumber);
                        sqlQuery += "\n";
                    }
                }
                sql = sqlTransBeginTry + "\n" + sqlQuery + "\n" + sqlTransEndTry + "\n" + sqlTransCatch;
                bool isSuccess = bool.Parse(SQLHelper.TExecuteScalar(sql).ToString());
                if (isSuccess)
                {
                    lblAlert.Text = "<font color='blue'><b>[Giao dịch thành công]</b></font>";                    
                }
                else
                {
                    lblAlert.Text = "<font color='red'><b>[Bạn phải đăng nhập trước]</b></font>";                    
                }
            }
            else
            {
                if (!isValid)
                {
                    lblAlert.Text = "<font color='red'><b>[Tài khoản của bạn không đủ]</b></font>";                    
                }
                else
                {
                    lblAlert.Text = "<font color='blue'><b>[Giao dịch thành công]</b></font>";                    
                }
            }
        }
    }
}
